'''
Author: 蚢
Date: 2021-05-14 14:52:36
Description: 
'''
###### 1.读写csv数据 #######
import csv
from collections import namedtuple

# 读取csv数据
with open('stocks.csv', 'rt') as f:
    # f.read()
    f_csv = csv.reader(f)

    headers = next(f_csv) # 得到第一行row_name
    Row = namedtuple('row', headers) # 使用命名元组,使数据一一对应

    for r in f_csv:
        print(Row(*r))
        break

    # headers: ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
    # row(Symbol='CAT', Price='78.29', Date='6/11/2007', Time='9:36am', Change='-0.23', Volume='225400'); 
    # 访问方式: row.Symbol

# 方法2:
with open('stocks.csv','rt') as f:
    f_csv = csv.DictReader(f)
    for row in f_csv:
        print(row['Symbol'])
        break

# 写入csv数据 :元组类
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
         ('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
         ('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),]

with open('stocks.csv','wt') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(rows)


# 方法2 :字典类
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007', 'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
        {'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007', 'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
        {'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007', 'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},]
with open('stocks.csv','wt') as f:
    f_csv = csv.DictWriter(f, headers)
    f_csv.writeheader()
    f_csv.writerows(rows)

## csv产生的数据都是字符串类型的，它不会做任何其他类型的转换。
##  pandas.read_csv() 


###### 2.读写JSON数据 #######

import json

data = {
    'name' : 'ACME',    
    'shares' : 100,
    'price' : 542.23
}
# 数据转换 -> json
json_str = json.dumps(data)

# json -> pyton
data = json.loads(json_str)

# 处理文件用dump和load,处理字符串用dumps和loads
with open('data.json', 'w') as f:
    json.dump(data, f)

with open('data.json', 'r') as f:
    data = json.load(f)

# python 对应的 json格式 
d = {
    'a': True,
    'b': False,
    'c': None,
}
data = json.dumps(d) # '{"a": true, "b": false, "c": null}'
# json数据过于复杂时,可以用pprint()函数更加美观
from pprint import pprint
pprint(data)


###### 3.解析简单的XML数据 #######

